package com.proxy.server.frontend.handler.request.show;

import com.proxy.parser.tree.sql.ast.SQLStatement;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlShowColumnsStatement;
import com.proxy.common.constant.PacketType;
import com.proxy.common.packet.BinaryPacket;
import com.proxy.common.packet.CommandPacket;
import com.proxy.server.backend.BackendConnection;
import com.proxy.server.backend.bio.BioBackendConnection;
import com.proxy.server.backend.nio.NioBackendConnection;
import com.proxy.server.context.AppContext;
import com.proxy.server.frontend.FrontendConnection;
import com.proxy.server.frontend.handler.request.select.ProxySqlReplaceUtil;
import com.proxy.server.frontend.handler.execute.BioSingleExecute;
import com.proxy.server.frontend.handler.execute.NioSingleExecute;

import java.io.UnsupportedEncodingException;

/**
 * Created by liufish on 16/8/1.
 */
public class ShowColumnsRequest {


    public static void doResponse(BinaryPacket bin, FrontendConnection connection, SQLStatement statement, String sql){

        BackendConnection backendConnection = null;

        try {

            backendConnection = AppContext.getInstance().getClients().get(0).borrowConnection();

            MySqlShowColumnsStatement  showColumnsStatement = (MySqlShowColumnsStatement)statement;

            ProxySqlReplaceUtil.replaceShowColumnsStatement(showColumnsStatement,backendConnection.getSchema());

            byte [] data = null;
            try {
                //backendConnection.getCharset()
                data = showColumnsStatement.toString().getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            CommandPacket packet = new CommandPacket(bin.packetId, PacketType.COM_QUERY,data);

            if(AppContext.getInstance().getFrontendProxy().isBio()){
                BioSingleExecute response = new BioSingleExecute();
                response.execute(connection,(BioBackendConnection)backendConnection,bin,packet);
            }else {
                NioSingleExecute execute = new NioSingleExecute();
                execute.execute(connection,(NioBackendConnection)backendConnection,bin,packet);
            }

        }finally {

            if(backendConnection != null){
                AppContext.getInstance().getClients().get(0).returnConnection(backendConnection);
            }
        }


    }
}
